package yxy.game.pm2.module.dungeon;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RMap;
import yxy.cherry.battle.module.Position;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.bubblebattle;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.module.rank.active.RankRushEnum;
import yxy.game.pm2.bean.module.rank.active.RankRushHandle;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.DungeonMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.task.TaskHandle;

/** 日常副本 */
public class DungeonHandle extends BattleModuleHandle {

	final public static int battleExpireDay = 1;// 战斗数据过期时间（天）

	protected String code() {
		return BattleType.DUNGEON.name();
	}

	public BattleMessage.BattleResponse battleResponse(String playerCode, bubblebattle _data) throws Exception {
		BattleHandle battleHandle = new BattleHandle();

		BattleModule battleModule = BattleModule.create(playerCode);
		battleModule.setType(BattleType.DUNGEON);
		battleModule.setCode(code());

		// 玩家的team
		TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
		battleModule.setTeamA(teamA);

		// 征战地图
		TeamModule teamB = teamDungeon(_data);
		battleModule.setTeamB(teamB);

		battleModule.setSettlement(SettlementDungeon.create(playerCode, _data.getId()));

//		PlayerBean playerBean = PlayerBean.get(playerCode);
//		int skipLevel = fomula.速战功能等级条件.intValue();
//		int skipVip = fomula.速战功能VIP条件.intValue();
//		battleModule.setSkip(playerBean.getViplevel() >= skipVip || playerBean.getLevel() >= skipLevel);

		battleModule.set(battleExpireDay);

		return battleHandle.battleResponse(battleModule);
	}

	public BattleMessage.BattleExecuteResponse battleResponseExecute(String playerCode, BattleMessage.BattleExecuteRequest request) throws Exception {
		BattleModule module = BattleModule.get(playerCode, code());
		return new BattleHandle().battleResponseExecute(module, request);
	}

	public TeamModule teamDungeon(bubblebattle _data) {
		TeamModule team = new TeamModule();

		RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:bubblebattle");
		JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(_data.getId())));
		ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
		});
		// 武将
		for (int i = 0; i < _data.getHeroid().length; i++) {
			Position position = Position.forValue(i + 1);
			int heroid = _data.getHeroid()[i];
			if (heroid == -1) continue;
			FighterModule fighterModule = fighterModules.get(i);
			team.addfighter(position, fighterModule);
		}
		// 神器
		WeaponModule weapon = WeaponModule.create(_data.getWeapondataid(), _data.getWeaponlv(), 0, 0, _data.getWeaponskilllv());
		team.setWeapon(weapon);

		// 信息
		team.setName(_data.getName());
		team.setHead(_data.getHeadid());
		team.setPower(team.power());

		return team;
	}

	/** 扫荡 */
	public Result sweep(String playerCode, int dungeonId, DungeonMessage.DungeonSweepResponse.Builder response) throws Exception {
		bubblebattle _data = DungeonHandle.data(dungeonId);
		DungeonModule dungeonModule = DungeonModule.get(playerCode, DungeonType.forNumber(_data.getType()));
		if (!dungeonModule.isOpen()) {
			return Result.ModuleNotOpen;// 副本尚未开启
		}
		try {
			if (dungeonModule.tryLock()) {
				// 检查关卡
				DungeonStage stage = dungeonModule.stage(dungeonId);
				if (!stage.getState().equals(DungeonStageState.可扫荡)) {
					return Result.DungeonCantSweep;// 关卡不能扫荡
				}

				// 次数判断
				int freetimes = dungeonModule.freeTimes();
				int paytimes = dungeonModule.payTimes();

				if (freetimes <= 0) {
					if (paytimes <= 0) {
						return Result.DungeonSweepTimesLack;// 扫荡次数不足
					}
					try {
						new CurrencyHandle().cost(playerCode, CCReason.日常副本, dungeonModule.cost(1));
					} catch (CurrencyNotEnoughException e) {
						return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
					}
				}

				// 处理次数
				dungeonModule.setTimes(dungeonModule.getTimes() + 1);
				dungeonModule.set();

				DungeonModule.checkTimes(playerCode);

				Collection<Currency> rewards = DungeonHandle.reward(dungeonId, 1);
				new CurrencyHandle().addCurrency(playerCode, CCReason.日常副本, rewards);
				response.addAllRewards(new CurrencyHandle().packItems(rewards));

				TaskHandle.handle(playerCode, TaskType.统计型_副本_日常副本_次数, 1);

				return Result.Success;
			}
		} catch (Exception e) {
		} finally {
			dungeonModule.unlock();
		}
		return Result.DataError;
	}

	/** 一键扫荡 */
	public Result sweepOneButton(String playerCode, int type, DungeonMessage.DungeonSweepOneButtonResponse.Builder response) throws Exception {
		DungeonModule dungeonModule = DungeonModule.get(playerCode, DungeonType.forNumber(type));
		if (!dungeonModule.isOpen()) {
			return Result.ModuleNotOpen;// 副本尚未开启
		}
		try {
			if (dungeonModule.tryLock()) {
				DungeonStage bestStage = null;
				for (DungeonStage stage : dungeonModule.getStages()) {
					if (stage.getState().equals(DungeonStageState.可扫荡)) {
						if (bestStage == null) {
							bestStage = stage;
							continue;
						}
						if (stage.getId() > bestStage.getId()) {
							bestStage = stage;
						}
					}
				}

				if (bestStage == null) {
					return Result.DungeonNoStageCanSweep;// 没有可扫荡的关卡
				}

				// 次数判断
				int freetimes = dungeonModule.freeTimes();
				int paytimes = dungeonModule.payTimes();
				int times = freetimes + paytimes;
				if (freetimes <= 0) {
					if (paytimes <= 0) {
						return Result.DungeonSweepTimesLack;// 扫荡次数不足
					}
					try {
						new CurrencyHandle().cost(playerCode, CCReason.日常副本, dungeonModule.cost(paytimes));
					} catch (CurrencyNotEnoughException e) {
						return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
					}
				}

				// 处理次数
				dungeonModule.setTimes(dungeonModule.getTimes() + times);
				dungeonModule.set();

				DungeonModule.checkTimes(playerCode);

				Collection<Currency> rewards = DungeonHandle.reward(bestStage.getId(), times);
				new CurrencyHandle().addCurrency(playerCode, CCReason.日常副本, rewards);
				response.addAllRewards(new CurrencyHandle().packItems(rewards));

				TaskHandle.handle(playerCode, TaskType.统计型_副本_日常副本_次数, times);
				TaskHandle.handle(playerCode, TaskType.统计型_副本关卡_次数, times);

				return Result.Success;
			}
		} catch (Exception e) {
		} finally {
			dungeonModule.unlock();
		}
		return Result.DataError;
	}

	/** 处理下一个关卡 */
	public void nextStage(String playerCode, int dungeonId) {
		bubblebattle _data = data(dungeonId);
		DungeonModule module = DungeonModule.get(playerCode, DungeonType.forNumber(_data.getType()));
		try {
			if (module.tryLock()) {

				DungeonStage stage = module.stage(dungeonId);
				if (stage != null) {
					stage.setState(DungeonStageState.可扫荡);
				}

				int nextDataId = dungeonId + 1;
				bubblebattle _nextdata = data(nextDataId);
				if (_nextdata != null) {
					DungeonStage nextStage = new DungeonStage();
					nextStage.setId(_nextdata.getId());
					nextStage.setState(DungeonStageState.可挑战);
					module.getStages().add(nextStage);
				}

				module.set();
			}
		} catch (Exception e) {
		} finally {
			module.unlock();
		}
		TaskHandle.handle(playerCode, TaskType.统计型_副本_日常副本_次数, 1);
	}

	static public bubblebattle data(int dungeonId) {
		return DataCenter.getData(dungeonId, bubblebattle.class);
	}

	static public Collection<Currency> reward(int dungeonId, int times) {
		ArrayList<Currency> rewards = new ArrayList<>();
		bubblebattle _data = data(dungeonId);
		if (_data != null) {
			rewards.addAll(Currency.create(_data.getRewardtype(), _data.getRewardid(), _data.getRewardnum()));
		}
		return rewards;
	}

}
